const keyUser = 'currentUser';

const clearUser = () => {
  wx.setStorageSync(keyUser, {});
};

const setUset = (user) => {
  wx.setStorageSync(keyUser, JSON.stringify(user));
};

const getUser = () => {
  try {
    let user = wx.getStorageSync(keyUser);
    if (user) {
      return JSON.parse(user);
    }
  } catch (e) {
    return {};
  }
};

const getToken = () => {
  let user = getUser();
  if (user && user.token !== undefined) {
    return user.token;
  }
  return '';
};

const loading = (title) => {
  title = title ? title : '玩命加载中...';
  wx.showLoading({
    title: title,
  })
};

const toastError = (content) => {
  wx.showToast({
    title: content,
    icon: 'none',
    duration: 3000
  })
};

const toastSuccess = (content) => {
  wx.showToast({
    title: content
  })
};

const request = (api, params = {}, method = 'GET', header = {}) => {
  return new Promise(function(resolve, reject) {
    if (!header['content-type']) {
      header["content-type"] = "application/json";
    }

    let token = getToken();
    if (token) {
      header["authorization"] = token;
    }

    wx.request({
      url: api,
      data:params,
      method:method,
      header:header,
      success:function(res){
        if (res.code === '200'){
          resolve(res.payload);
        }
      },
      fail:function(err){
        reject(err);
      }
    })
  });
};


module.exports = {
  clearUser,
  setUset,
  getUser,
  getToken,
  loading,
  toastError,
  toastSuccess,
  request
};
